﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace ProgressBarTest.Controls
{
    /// <summary>
    /// 具有动画效果进度条控件
    /// </summary>
    public class DynamicProgressBar : ProgressBar
    {
        /// <summary>
        /// 最小值
        /// </summary>
        private const double MinValue = 0.0;
        /// <summary>
        /// 最大值
        /// </summary>
        private const double MaxValue = 100.0;
        /// <summary>
        /// 计时器运行次数
        /// </summary>
        private const int TimerRunTimes = 50;

        #region 变量
        /// <summary>
        /// 进度条的值
        /// </summary>
        private double _barValue;
        /// <summary>
        /// 计时器运行时，进度条增加的步长
        /// </summary>
        private double _barValStep;
        /// <summary>
        /// 进度条动画计时器
        /// </summary>
        private readonly DispatcherTimer _timer;
        #endregion

        #region 构造函数
        public DynamicProgressBar()
        {
            DefaultStyleKey = typeof(DynamicProgressBar);

            _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(2.0) };
            _timer.Tick += Ontimer_Tick;
        }
        #endregion

        #region 属性

        public double BarValue
        {
            get { return _barValue; }
            set
            {
                if (value < MinValue || value > MaxValue)
                {
                    throw new ArgumentOutOfRangeException("value", "进度条值的范围是0-100");
                }
                _barValue = value;
                _barValStep = value / TimerRunTimes;
                Value = 0.0;

                if (!_timer.IsEnabled)
                    _timer.Start();
            }
        }
        #endregion

        #region 计时器
        private void Ontimer_Tick(object sender, EventArgs e)
        {
            if (BarValue - Value <= 1.0)
            {
                Value = BarValue;
                _timer.Stop();
                return;
            }
            Value += _barValStep;
        }
        #endregion

    }
}
